<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<!-- 消息连接组件 -->
<template>
  <view v-show="!JIMConnect" class="nav " :class="fixed?'fixed':''" :style="[{top:CustomBar + 'px'}]">
    <view class=" cu-bar bg-white solid-bottom padding-tb padding-lr-sm">
      <view class="action">
        <text class="cuIcon-roundclose text-red"></text>
        聊天已断开,正在重连...
      </view>
      <view class="action">
        <button class="cu-btn bg-green sm" @tap="reconnectChat">手动重连</button>
      </view>
    </view>
  </view>
</template>

<script>
/**
 * Copyright (C) 2018-2019
 * All rights reserved, Designed By www.joolun.com
 * 注意：
 * 本软件为www.joolun.com开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
const app = getApp();
import JimUtil from '@/utils/jim-util' // JLIM工具库

export default {
  props: {
    fixed: { // 是否悬浮
      type: Boolean,
      default: false
    }
  },
  onShow() {},
  watch: {
    'IMdata.IMloginStatus'(newVal, oldVal){
      // 登录状态更改
      if (newVal)
        this.JIMConnect = newVal
    },
    JIMConnect: function(newVal, oldVal) {},
  },
  mounted() {
    //超时监听
    uni.$on('JIMDisconnect', (data) => {
      this.JIMConnect = false
    })
    //登录监听
    uni.$on('JIMLogin', (data) => {
      this.JIMConnect = true
    })
  },
  data() {
    return {
      CustomBar: this.CustomBar,
      JIMConnect: true,
      IMdata: app.globalData.IMdata
    };
  },
  methods: {
    // 重连OpenIM
    reconnectChat() {
      //登出JLIM
      uni.showLoading()
      JimUtil.IMloginOut()
      let pages = getCurrentPages()
      let pagesUrls = []
      pagesUrls = pages.reverse().map((item) => {
        if (pagesUrls.length < 3) {
          pagesUrls.push(this.getCurrentPageUrlWithArgs(item))
        }
        return this.getCurrentPageUrlWithArgs(item)
      })
      pagesUrls = pagesUrls.reverse()
      uni.setStorageSync("jump_im_connect_page", JSON.stringify(pagesUrls)) //保存跳转到im重连之前的页面
      // APP需要重启应用OpenIM才能重连
      // #ifdef APP-PLUS
      plus.runtime.restart();
      // #endif
      uni.reLaunch({
        url: '/pages/home/index',
        complete: () => {
          IMUtil.reloginIM()
        }
      });
      uni.hideLoading()
    },
    // url: 页面及参数
    getCurrentPageUrlWithArgs(currentPage) {
      const url = currentPage.route;
      const options = currentPage.options;
      let urlWithArgs = `/${url}?`;
      for (let key in options) {
        const value = options[key];
        urlWithArgs += `${key}=${value}&`;
      }
      urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
      return urlWithArgs;
    }
  }
}
</script>

<style>
</style>
